﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using PriceLibrary.PriceService;

using VDataAdapter.Communication;
using VDataAdapter.QueueManagement;
using VDataAdapter.EventManagement;

namespace VDataAdapter.WorkerManagement
{
    class PutThroughTransactionWorkerException : Exception
    {
        public PutThroughTransactionWorkerException() : base() { }
        public PutThroughTransactionWorkerException(string msg) : base(msg) { }
        public PutThroughTransactionWorkerException(string msg, Exception inner) : base(msg, inner) { }
    }

    class PutThroughTransactionWorker : Worker
    {
        private VDataCommunicator _sender;

        private IEventProviderQueue _eQueue;

        private EventQueueChecker _queueChecker;

        /// <summary>
        /// Let it starts only after transactions is sent
        /// </summary>
        /// <param name="waitTransaction"></param>
        /// <param name="sender"></param>
        /// <param name="eQueue"></param>
        public PutThroughTransactionWorker(string parentName,ManualResetEvent waitTransaction, VDataCommunicator sender, IEventProviderQueue eQueue)
            : base(waitTransaction, null, true)
        {
            _name = parentName+"-PutThroughTransactionWorker";
            _sender = sender;
            _eQueue = eQueue;
            _queueChecker = new EventQueueChecker(eQueue);
        }

        public bool StopCheckingQueue
        {
            set { _queueChecker.StopCheckingQueue = value; }
            get { return _queueChecker.StopCheckingQueue; }
        }

        override
        public void StopWork()
        {
            StopCheckingQueue = true;
        }

        protected override void DoWork(object data)
        {
            try
            {
                var e = (PtTransactionsChangedEvent)_queueChecker.CheckingQueue(EventType.PutThroughTransaction);

                // sort transactions
                List<Transaction> collection = e.Transactions.Distinct().OrderBy(c => int.Parse(c.Time)).ToList();

                foreach (Transaction item in collection)
                {
                    if(item.Symbol == "VNM")
                        Console.Write("t");
                    _sender.SendTransactionPutThrough(item);
                }

            }
            catch (Exception ex)
            {
                _status = "Opps I have an error during work";
                throw new PutThroughTransactionWorkerException("Unknown exception: ", ex);
            }
        }
    }
}
